<!--
 * @Date: 2022-06-13 14:29:31
 * @LastEditTime: 2022-12-22 11:43:29
 * @Description: 登录
-->
<template>
	<view class="page-wrap">
		<view class="loginbox">
			<view class="header-image">
				<image src="/static/images/login_header.png" mode="widthFix"></image>
			</view>
			<view class="content-wrap">
				<!-- 手机号显示区域 -->
				<view class="phone-display" v-if="loginType === 'quick'">
					<view class="phone-number">{{ maskPhoneNumber }}</view>
					<view class="service-text">XXXXXX服务认证</view>
				</view>

				<!-- 表单登录区域 -->
				<view class="form-container" v-if="loginType === 'code'">
					<view class="input-group">
						<view class="input-item">
							<input type="text" v-model="form.mobile" placeholder="请输入您的手机号" class="custom-input"
								maxlength="11" />
							<text class="clear-icon" v-if="form.mobile" @click="form.mobile = ''">
								×
							</text>
						</view>
						<view class="input-item">
							<input type="text" v-model="form.code" placeholder="输入验证码" class="custom-input"
								maxlength="6" />
							<button class="send-code-btn" :class="{ disabled: disabledCode }" @click="getCode">
								{{ codeSecond ? `${codeSecond}秒后重新获取` : "发送验证码" }}
							</button>
						</view>
					</view>
				</view>

				<!-- 登录按钮区域 -->
				<view class="btn-wrap">
					<view class="action-btn" @click="handleLogin">
						<image
							:src="loginType === 'quick' ? '/static/images/yjdl.png' : '/static/images/login.png'"
							mode="widthFix" class="btn-image" />
					</view>
				</view>

				<!-- 切换登录方式 -->
				<view class="action-links">
					<view class="switch-login" @click="switchLoginType">
						{{ loginType === "quick" ? "验证码登录" : "本机号码一键登录" }}
					</view>
				</view>
			</view>

			<view class="bottom-section">
				<image src="/static/images/login_bg.png" mode="widthFix" class="bottom-cat-image" />
				<view class="agree-box">
					<image :src="agreeChecked ? '/static/images/xz.png' : '/static/images/wxz.png'"
						mode="aspectFit" class="checkbox-image" @click="checkboxChange" />
					<view class="agree-box-text">
						同意
						<text class="book-style" @click="$common.toRule(1)">
							《用户协议》
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import {
		encrypt
	} from '../../utils/crypto.js'

	export default {
		data() {
			return {
				customStyle: {
					background: "#1d1d62",
					color: "#fff",
					"border-color": "#1d1d62",
				},
				headImg: "https://ypay.hui-xiang.cn/uploads/other/avatar3.png",
				nickName: "默认微信用户",
				agreeChecked: false,
				anShow: false,
				optionsData: "",
				form: {
					mobile: "",
					code: "",
				},
				formRules: {
					mobile: [{
							required: true,
							message: "请输入手机号"
						},
						{
							pattern: /^1[3-9]\d{9}$/,
							message: "请输入正确的手机号"
						},
					],
					code: [{
						required: true,
						message: "请输入验证码"
					}, ],
				},
				sysConfig: "",
				codeSecond: 0,
				disabledCode: false,
				timer: null,
				loginType: "quick", // 'code': 验证码登录, 'quick': 一键登录
				maskPhoneNumber: "197****3456", // 脱敏的手机号
				isGettingPhone: false, // 是否正在获取手机号
			};
		},
		computed: {
			...mapGetters(["appConfig"]),
			// 获取按钮文字
			getActionButtonText() {
				return this.loginType === "quick" ? "本机号码一键登录" : "登录";
			}
		},
		onLoad(options) {
			plus.android.importClass("android.telephony.TelephonyManager");
			let context = plus.android.importClass("android.content.Context");
			let TelephonyManager = plus.android
				.runtimeMainActivity()
				.getSystemService(context.TELEPHONY_SERVICE);

			let OperatorName = TelephonyManager.getSimOperatorName();
			let phoneNumber = TelephonyManager.getLine1Number();

			console.log(`运行商名称:${OperatorName}`);
			console.log(`手机号:${phoneNumber}`);

			console.log("options", options);
			this.optionsData = options;
			// this.login()
			this.$store.dispatch("getAppConfig").then((res) => {
				this.sysConfig = res.data;
			});
		},
		onShow() {
			this.tokens = uni.getStorageSync("token");
		},
		methods: {
			// 获取本机手机号
			async getPhoneNumber() {
				if (this.isGettingPhone) return;
				this.isGettingPhone = true;

				try {
					// 导入 Android 相关类
					plus.android.importClass("android.telephony.TelephonyManager");
					let context = plus.android.importClass("android.content.Context");

					// 获取 TelephonyManager 实例
					let TelephonyManager = plus.android
						.runtimeMainActivity()
						.getSystemService(context.TELEPHONY_SERVICE);

					// 获取手机号
					let phoneNumber = TelephonyManager.getLine1Number();

					if (phoneNumber) {
						// 处理手机号格式，确保是标准的11位手机号
						phoneNumber = phoneNumber.replace(/\+86/, '').replace(/\s/g, '');
						if (/^1[3-9]\d{9}$/.test(phoneNumber)) {
							this.form.mobile = phoneNumber;
							return true;
						}
					}

					this.showToast("获取手机号失败，请使用验证码登录");
					return false;
				} catch (error) {
					console.error('获取手机号错误:', error);
					this.showToast("获取手机号失败，请使用验证码登录");
					return false;
				} finally {
					this.isGettingPhone = false;
				}
			},

			// 处理一键登录
			async handleQuickLogin() {
				if (!this.agreeChecked) {
					this.showToast("请先同意协议");
					return;
				}

				// 尝试获取手机号
				const success = await this.getPhoneNumber();
				if (!success) {
					// 如果获取手机号失败，自动切换到验证码登录
					this.loginType = "code";
					return;
				}

				// 构造登录数据
				const loginData = {
					type: 2, // 一键登录
					mobile: encrypt(this.form.mobile),
				};

				// 发起登录请求
				this.req({
					url: "/v1/user/loginUser",
					data: loginData,
					Loading: true,
					success: (res) => {
						console.log(res);
						if (res.code === 200) {
							this.handleLoginSuccess(res.data);
						} else {
							this.showToast(res.msg);
						}
					},
				});
			},

			// 处理登录
			handleLogin() {
				if (this.loginType === "quick") {
					this.handleQuickLogin();
					return;
				}

				if (!this.validateForm()) return;

				if (!this.agreeChecked) {
					this.showToast("请先同意协议");
					return;
				}

				const loginData = {
					type: 1, // 验证码登录
					mobile: encrypt(this.form.mobile),
					code: this.form.code,
				};

				this.req({
					url: "/v1/user/loginUser",
					data: loginData,
					Loading: true,
					success: (res) => {
						if (res.code === 200) {
							this.handleLoginSuccess(res.data);
						} else {
							this.showToast(res.msg);
						}
					},
				});
			},
			getUserInfo() {
				this.req({
					url: "/v1/user/info",
					data: {},
					Loading: false,
					success: (res) => {
						if (res.code == 200) {
							const newData = res.data.data || {};
							this.userInfo = newData;
							this.$store.dispatch("setUserInfo", newData);
						}
					},
				});
			},
			// 统一处理登录成功
			handleLoginSuccess(data) {
				uni.setStorageSync("token", `${data.access_token}`);
				this.$store.dispatch("getUserInfo");
				uni.reLaunch({
					url: "/pages/index/index",
				});
			},

			// 切换登录方式
			async switchLoginType() {
				const newType = this.loginType === "code" ? "quick" : "code";

				if (newType === "quick") {
					// 切换到一键登录时，尝试获取手机号
					const success = await this.getPhoneNumber();
					if (!success) {
						return; // 如果获取失败，保持在当前模式
					}
				}

				this.loginType = newType;
				if (newType === "code") {
					this.resetForm();
				}
			},

			// 重置表单
			resetForm() {
				this.form.mobile = "";
				this.form.code = "";
				this.codeSecond = 0;
				this.disabledCode = false;
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},

			// 统一表单验证
			validateForm(fields = ["mobile", "code"]) {
				for (const field of fields) {
					const rules = this.formRules[field];
					const value = this.form[field];

					if (!rules) continue;

					for (const rule of rules) {
						if (rule.required && !value) {
							this.showToast(rule.message);
							return false;
						}
						if (rule.pattern && !rule.pattern.test(value)) {
							this.showToast(rule.message);
							return false;
						}
					}
				}
				return true;
			},

			// 统一提示方法
			showToast(title, type = "none") {
				uni.showToast({
					title,
					icon: type,
					mask: true,
				});
			},

			checkboxChange() {
				this.agreeChecked = !this.agreeChecked;
			},

			// 获取验证码
			getCode() {
				// 确保手机号存在且格式正确
				if (!this.form.mobile) {
					this.showToast("请输入手机号");
					return;
				}

				if (!/^1[3-9]\d{9}$/.test(this.form.mobile)) {
					this.showToast("请输入正确的手机号");
					return;
				}

				// 开始倒计时
				this.codeSecond = 60;
				this.disabledCode = true;
				this.timer = setInterval(() => {
					if (this.codeSecond >= 1) {
						this.codeSecond--;
					} else {
						this.disabledCode = false;
						clearInterval(this.timer);
						this.timer = null;
					}
				}, 1000);

				const smsData = {
					mobile: this.form.mobile,
					type: 2, // 2-登录
				};

				this.req({
					url: "/v1/sms/send",
					method: "POST",
					data: smsData,
					Loading: true,
					success: (res) => {
						if (res.code === 200) {
							this.showToast("验证码已发送", "success");
						} else {
							// 如果发送失败，停止倒计时
							this.codeSecond = 0;
							this.disabledCode = false;
							if (this.timer) {
								clearInterval(this.timer);
								this.timer = null;
							}
							this.showToast(res.msg);
						}
					},
					fail: (err) => {
						// 请求失败也需要停止倒计时
						this.codeSecond = 0;
						this.disabledCode = false;
						if (this.timer) {
							clearInterval(this.timer);
							this.timer = null;
						}
						this.showToast("发送失败，请重试");
					}
				});
			},
		},
		// 组件销毁时清理定时器
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		}
	};
</script>

<style lang="scss">
	.page-wrap {
		min-height: 100vh;
		background-image: url("/static/images/backg.png");
		background-size: cover;
		background-repeat: no-repeat;
		background-position: center;
	}

	.loginbox {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		position: relative;
	}

	.header-image {
		margin-top: 50rpx;
		width: 100%;

		image {
			width: 100%;
		}
	}

	.content-wrap {
		flex: 1;
		padding: 0 40rpx;
	}

	.phone-display {
		text-align: center;
		margin-top: 100rpx;

		.phone-number {
			font-size: 48rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
		}

		.service-text {
			font-size: 28rpx;
			color: #666;
		}
	}

	.form-container {
		margin-top: 60rpx;
	}

	.input-group {
		.input-item {
			position: relative;
			margin-bottom: 42rpx;

			.custom-input {
				width: 100%;
				height: 100rpx;
				background: #fff;
				border-radius: 12rpx;
				padding: 0 30rpx;
				font-size: 28rpx;
				box-sizing: border-box;
				border: 4rpx solid #333;
				color: #333;

				&::placeholder {
					color: #999;
				}
			}

			.clear-icon {
				position: absolute;
				right: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				color: #999;
				font-size: 40rpx;
				line-height: 1;
				padding: 10rpx;
			}

			.send-code-btn {
				position: absolute;
				right: 20rpx;
				top: 50%;
				transform: translateY(-50%);
				background: transparent;
				border: none;
				font-weight: 400;
				font-size: 32rpx;
				color: #b73931;
				padding: 20rpx;
				line-height: 1;

				&.disabled {
					color: #999;
				}

				&::after {
					border: none;
				}
			}
		}
	}

	.btn-wrap {
		margin-top: 62rpx;
		width: 100%;
		box-sizing: border-box;

		.action-btn {
			width: 100%;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.btn-image {
				width: 100%;
				height: 100rpx;
				transition: all 0.3s ease; // 添加过渡效果
			}

			&:active .btn-image {
				opacity: 0.8; // 点击时的效果
			}
		}
	}

	.action-links {
		display: flex;
		align-items: center;
		margin-top: 40rpx;
		justify-content: space-between;

		.switch-login {

			text-align: center;
			font-size: 32rpx;
			color: #9e1e2d;
			margin-top: 16rpx;
			margin: auto
		}
	}

	.bottom-section {
		position: relative;
		width: 100%;

		.bottom-cat-image {
			width: 100%;
			display: block;
			vertical-align: bottom;
		}

		.agree-box {
			position: absolute;
			bottom: 40rpx;
			left: 0;
			right: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1;

			.checkbox-image {
				width: 48rpx;
				height: 48rpx;
				margin-right: 10rpx;
			}

			.agree-box-text {
				font-weight: 400;
				font-size: 32rpx;
				color: #000000;

				.book-style {
					color: #333;
					text-decoration: underline;
				}
			}
		}
	}

	::v-deep .u-checkbox {
		display: none;
	}

	// 修改输入框右侧图标的样式
	::v-deep .uni-input-wrapper {
		.uni-clear-icon {
			color: #333;
		}
	}

	// 移除原有的按钮样式
	.login-btn {
		display: none;
	}
</style>